import io
import tkinter as tk
from tkinter import *
from tkinter import messagebox, filedialog
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import image as mpimg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.projections import polar

read_from_file = False


def open_file_dialog():
    global read_from_file
    read_from_file = True
    filepath = filedialog.askopenfilename(
        title="选择文件",  # 对话框标题
        filetypes=[  # 文件类型过滤器
            ("CSV files", "*.xlsx"),
            ("CSV files", "*.csv"),
            ("All files", "*.*")
        ]
    )

    return filepath


class Draw:
    def __init__(self, main_window):
        self.button_frame = None
        self.labels_entry = None
        self.data_entry = None
        self.input_frame = None
        self.file_menu = None
        self.menu_bar = None
        self.canvas = None
        self.ax = None
        self.fig = None
        self.root = Toplevel(main_window)
        self.root.title("图表绘制工具")
        self.create_widgets()

    def create_widgets(self):
        # 绘图区域
        self.fig, self.ax = plt.subplots()
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=5, sticky='ew', ipadx=5, ipady=60)

        # 菜单
        self.menu_bar = tk.Menu(self.root)
        self.root.config(menu=self.menu_bar)

        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="保存图片", command=self.save_figure)
        self.menu_bar.add_cascade(label="文件", menu=self.file_menu)

        # 输入区域
        self.input_frame = Frame(self.root)
        self.input_frame.grid(row=1, column=0, sticky="ew")
        Label(self.input_frame, text="数据（逗号分隔）:").pack(side=tk.LEFT)
        self.data_entry = Entry(self.input_frame)
        self.data_entry.pack(side=tk.LEFT)
        Label(self.input_frame, text="标签（逗号分隔）:").pack(side=tk.LEFT)
        self.labels_entry = Entry(self.input_frame)
        self.labels_entry.pack(side=tk.LEFT)

        # 按钮区域
        self.button_frame = Frame(self.root)
        self.button_frame.grid(row=2, column=0, rowspan=2, sticky="ns")

        Button(self.button_frame, text="绘制柱状图", command=self.draw_bar_chart).pack(side=tk.LEFT)
        Button(self.button_frame, text="绘制饼状图", command=self.draw_pie_chart).pack(side=tk.LEFT)
        Button(self.button_frame, text="绘制折线图", command=self.draw_line_chart).pack(side=tk.LEFT)
        Button(self.button_frame, text='绘制散点图', command=self.draw_dot_chart).pack(side=tk.LEFT)
        Button(self.button_frame, text='绘制面积图', command=self.draw_area_chart).pack(side=tk.LEFT)
        Button(self.button_frame, text="绘制柱状迭加图", command=self.draw_stacked_bar_chart).pack(side=tk.LEFT)
        # 调整画布和按钮区域的权重
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(0, weight=1)

    # 如果有文件被选中，更新标签内容以显示文件路径
    # if filepath:
    #     file_label.config(text=f"选中的文件: {filepath}")
    def twe_var_data(self):
        global read_from_file
        excel_file_path = open_file_dialog()
        if read_from_file:
            columns_data = []
            df = pd.read_excel(excel_file_path)
            for col in df.columns:
                column_data = df[col].tolist()
                columns_data.append(column_data)
            return columns_data
        else:
            columns_data = []
            data = [float(x) for x in self.data_entry.get().split(',')]
            labels = self.labels_entry.get().split(',')
            columns_data.append(data)
            columns_data.append(labels)
            return columns_data

    def draw_bar_chart(self):
        global read_from_file
        data_list = self.twe_var_data()
        labels = data_list[0]
        data = data_list[1]
        self.ax.clear()
        self.ax.bar(labels, data)
        self.canvas.draw()
        read_from_file = False

    def draw_pie_chart(self):
        global read_from_file
        data_list = self.twe_var_data()
        labels = data_list[0]
        data = data_list[1]
        self.ax.clear()
        self.ax.pie(data, labels=labels, autopct='%1.1f%%')
        self.canvas.draw()

    def draw_line_chart(self):
        global read_from_file
        data_list = self.twe_var_data()
        labels = data_list[0]
        data = data_list[1]
        self.ax.clear()
        self.ax.plot(labels, data, marker='o')
        self.canvas.draw()
        read_from_file = False

    def draw_dot_chart(self):
        global read_from_file
        data_list = self.twe_var_data()
        labels = data_list[0]
        data = data_list[1]
        self.ax.clear()
        self.ax.scatter(data, labels, marker='o')
        self.canvas.draw()
        read_from_file = False

    def draw_area_chart(self):
        global read_from_file
        data_list = self.twe_var_data()
        labels = data_list[0]
        data = data_list[1]
        self.ax.clear()
        self.ax.fill_between(data, labels, alpha=0.4)
        self.ax.grid(True)
        self.canvas.draw()
        read_from_file = False

    def autolabel(self, rect):
        for rect in rect:
            height = rect.get_height()
            self.ax.annotate('{}'.format(height),
                             xy=(rect.get_x() + rect.get_width() / 2, height),
                             xytext=(0, 3),  # 3 points vertical offset
                             textcoords="offset points",
                             ha='center', va='bottom')

    def draw_stacked_bar_chart(self):
        global read_from_file
        width = 0.35

        data_list = self.twe_var_data()
        print(data_list)
        labels = data_list[0]
        print(labels)
        data1 = data_list[1]
        data2 = data_list[2]
        print(data1)
        print(data2)
        x = np.arange(len(labels))
        rec1 = self.ax.bar(x - width / 2, data1, width, label='data1')
        rec2 = self.ax.bar(x + width / 2, data2, width, bottom=data1, label='data2')
        self.ax.set_ylabel('Scores')
        self.ax.set_title('Scores by group and gender')
        self.ax.set_xticks(x)
        self.ax.set_xticklabels(labels)
        self.ax.legend()
        self.autolabel(rec1)
        self.autolabel(rec2)
        self.ax.grid(True)
        self.canvas.draw()
        read_from_file = False

    def save_figure(self):
        # 弹出对话框让用户选择保存路径
        file_path = filedialog.asksaveasfilename(defaultextension=".png",
                                                 filetypes=[("PNG Image", "*.png"),
                                                            ("JPEG Image", "*.jpg"),
                                                            ("SVG Image", "*.svg")])
        if file_path:
            self.fig.savefig(file_path, dpi=300)
